package com.webchat.controller;

import com.webchat.Utils.RandomStringUtil;
import com.webchat.Utils.SessionUtils;
import com.webchat.dao.UsersDao;
import com.webchat.model.UsersEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * Created by YongX on 2016/8/20.
 */
/**
 * type
 * 1 = 收到新消息
 * 2 = 上线
 * 3 =
 * 4 =
 * 5 = 断开
 */

@ServerEndpoint("/chat/{uid}/{token}")
public class WebsocketController {
    private static Log logger = LogFactory.getLog(WebsocketController.class);

    /**
     * 打开连接时触发
     * @param uid
     * @param token
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("uid") Integer uid, @PathParam("token") String token, Session session){
        UsersDao usersDao = new UsersDao();
        UsersEntity user = usersDao.getUser(uid);
        if (user == null){
            logger.info("没有发现用户："+user.getId());
            closeSession(session);
        }else if (!user.getChatToken().equals(token)){
            logger.info("验证用户："+user.getId()+"失败");
            closeSession(session);
        }else {
            if (SessionUtils.hasConnection(user.getId()) && user.getId() > 0){
                closeSession(SessionUtils.clients.get(user.getId()));
                SessionUtils.remove(user.getId());
            }
            SessionUtils.put(user.getId(), session);
            user.setChatToken(RandomStringUtil.getRandomString(64));
            usersDao.update(user);
            SessionUtils.sendOnlineMessage(user);
            logger.info("用户"+user.getName()+"("+user.getId()+")已成功登陆服务器");
        }
        usersDao.closeSession();
    }


    /**
     * 收到客户端消息时触发
     * @param message
     * @param session
     * @return
     * 消息模板
     {
        "type":1  1 = 好友消息， 2=好友上线 3 = 好友下线
            "msg":[
            "senduid":2,
            "acceptuid":3,
            "content":"这只是一个消息内容而已"
        ]
    }
     */
    @OnMessage
    public String onMessage(String message, Session session) {
        Integer uid = SessionUtils.getUidBySession(session);
        logger.info("UID:" + uid + "发送消息-" + message);
        JSONObject json = new JSONObject(message);
        if (json.getInt("type") == 1){
            JSONObject msgJson = json.getJSONObject("msg");
            Integer accpetUid = msgJson.getInt("acceptuid");
            String content  = msgJson.getString("content");
            try {
                SessionUtils.sendMessageToUser(uid, accpetUid, content);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (EncodeException e) {
                e.printStackTrace();
            }
        }
        return "OK";
    }

    /**
     * 异常时触发
     * @param session
     */
    @OnError
    public void onError(Throwable throwable, Session session) {
        throwable.printStackTrace();
        Integer uid =  SessionUtils.removeSession(session);
        if (uid > 0){
            sendDisMsg(uid);
            logger.info("UID:"+uid+" 发生错误断开了");
        }else {
            logger.info("没有发现用户");
        }
    }
    @OnClose
    public void onClose(Session session) {
        Integer uid =  SessionUtils.removeSession(session);
        if (uid > 0){
            sendDisMsg(uid);
            logger.info("UID:"+uid+"断开了连接");
        }else {
            logger.info("没有发现用户");
        }
    }

    private void closeSession(Session session){
        try {
            if (session.isOpen()){
                session.close();
            }
        } catch (IOException e) {
            logger.info("--------------------会话关闭异常---------------------");
//            e.printStackTrace();
        }
    }

    private void sendDisMsg(Integer uid){
        UsersDao usersDao = new UsersDao();
        UsersEntity user = usersDao.getUser(uid);
        SessionUtils.sendDisconnectMessage(user);
        usersDao.closeSession();
    }
}
